﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;


using MINERP.CustomerManage.StartOrder;
using MINERP.ComControls;
using MINERP.CustomerManage;
using MINERP.CustomerManage.Controller;
using MINERP.BLL.CustomerManage;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using System.Diagnostics;
using Leadtools.WinForms;
using MINERP.COM;
using System.Threading;
using System.Reflection;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MINERP.BLL.Common;
using MINERP.ComControls.Extension;


namespace MINERP.CustomerManage
{
    public partial class FrmManage : FrmParent
    {
        /// <summary>
        /// 开单窗体
        /// </summary>
        private FrmStartOrder _startOrder = null;
        /// <summary>
        /// 编辑订单产品窗体
        /// </summary>
        private FrmEditOrder _editOrder = null;
        /// <summary>
        /// 查询窗体
        /// </summary>
        private FrmSearch _searchFrm = null;
        /// <summary>
        /// 订单包操作类
        /// </summary>
        private OrderBagController _controller = null;

        /// <summary>
        /// 订单产品操作类
        /// </summary>
        private OrderInfoController _infoController = null;
        /// <summary>
        /// 产品生产过程类
        /// </summary>
        private WorkOrderFlowListController _flowController = null;
        /// <summary>
        /// 照片信息控制类
        /// </summary>
        private PhotoInfoController _photoController = null;
        /// <summary>
        /// 用户沟通控制类
        /// </summary>
        private TalkRecordController _talkRecordController = null;
        /// <summary>
        /// 查询控制类
        /// </summary>
        private SearchController _searchController = null;
        /// <summary>
        /// 快速查询的查询条件
        /// </summary>
        private RapidCondition _condition = null;
        /// <summary>
        /// 记录订单的行
        /// </summary>
        private int _rowHandle = 0;
        /// <summary>
        /// 记录订单的关联索引
        /// </summary>
        private int _relationIndex = 0;
        private int _clickHandle = 0;

        /// <summary>
        /// 是否显示缩略图的模式
        /// </summary>
        private bool _isPhotoMode = false;
        /// <summary>
        /// 当前选择的产品号
        /// </summary>
        private int _orderProductID = 0;

        /// <summary>
        /// 获得焦点的订单
        /// </summary>
        private OrderBagEntity _focusOrderBag = null;
        /// <summary>
        /// 获得焦点的产品
        /// </summary>
        private OrderInfoEntity _focusOrderInfo = null;

        /// <summary>
        /// 订单的状态
        /// </summary>
        public int OrderStatus = 0;

        /// <summary>
        /// 停止、恢复的原因
        /// </summary>
        public string StopRemark { get; set; }
        public FrmPhotoMove fpm;
        public bool IsMovePhotoRun { get; set; }            //移动照片的页面是否正在运行

        //当前被选中产品的基本信息
        public MODEL.CustomerManage.CurrentStyleProduct currentStyleProduct = new MINERP.MODEL.CustomerManage.CurrentStyleProduct();


        //开单，编辑订单的数量控制
        public int StartOrderNum = 0;
        public int EditOrderNum = 0;
        private BLL.CustomerManage.StartOrderBLL SOBLL = new MINERP.BLL.CustomerManage.StartOrderBLL();
        public static bool IsAddedOrderTree = false;        //是否已加载开单树
        public static List<StartOrderBLL.OrderTree> Tree = new List<StartOrderBLL.OrderTree>();     //开单树

        //委托 移动照片的页面使用
        delegate void ClosePhotoMove();
        [DllImport("shell32.dll ")]
        private static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);


        public FrmManage()
        {
            try
            {
                _controller = new OrderBagController();
                _infoController = new OrderInfoController();
                _flowController = new WorkOrderFlowListController();
                _talkRecordController = new TalkRecordController();
                _photoController = new PhotoInfoController();
                _searchController = new SearchController(_controller);

                _condition = new RapidCondition();

                //多线程异步处理
                Control.CheckForIllegalCrossThreadCalls = false;

                InitializeComponent();
                base.InitiAuthority();

                //设置所有节点，并缓存在内存中
                _controller.SetAllTechs();
                //线程获取开单树 
                ThreadGetTree();
                RushPanlOrderInfoStatus();

                gridViewOrder.ShowRowIndicator(50);
                gridViewProduct.ShowRowIndicator(50);
                //CardProduct.ShowRowIndicator(50);
                gridViewProductProcess.ShowRowIndicator(50);
                gridViewPhotoInfo.ShowRowIndicator(50);
                gridViewTalkRecord.ShowRowIndicator(50);
                gridViewInfomation.ShowRowIndicator(50);
                gridView1.ShowRowIndicator(50);
                gridView2.ShowRowIndicator(50);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        /// <summary>
        /// 线程获取开单树
        /// </summary>
        public void ThreadGetTree()
        {
            try
            {
                //线程获取开单树
                Thread thOrderTree = new Thread(GetTree);
                thOrderTree.Start();
            }
            catch { }
        }

        /// <summary>
        /// 加载开单树
        /// </summary>
        public void GetTree()
        {
            try
            {
                Tree.Clear();
                //等待开单目录结构思想：
                //商户层固定，每个商户下“已开单”临时目录固定
                //1 客户层中只有照片，就形成一个产品，产品名从右边获取
                //2 客户层中有照片和目录，提示有照片和目录同时存在，是否要继续开单，如果是，就形成一个产品，产品名从右边获取
                //3 客户层中只有目录，按三层结构开单
                //----------------------------------------
                string totalPath = SOBLL.GetStartOrderPath();
                string directoryName = totalPath.Substring(totalPath.LastIndexOf("\\") + 1);
                if (directoryName != "等待开单")
                    MessageBox.Show("等待开单的目录设置不正确，请在后台重新设置！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                totalPath += "\\" + userName;                                   //每个开单员只能操作本人的开单文件夹
                string[] directorys = Directory.GetDirectories(totalPath);
                foreach (string directory in directorys)
                {
                    if (IsEmpty(directory, true))
                        continue;
                    if (Directory.GetDirectories(directory).Length > 1)
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                        StartOrderBLL.OrderTree ot = new StartOrderBLL.OrderTree();
                        ot.ShopName = directoryInfo.Name + "1";                     //商户层，最后一位1表示处于第一层
                        ot.ShopText = directoryInfo.Name;
                        ot.ShopFullName = directoryInfo.FullName;
                        Tree.Add(ot);

                        string[] subDirectorys = Directory.GetDirectories(directory);
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (IsEmpty(subDirectory, false))
                                continue;
                            DirectoryInfo subInfo = new DirectoryInfo(subDirectory);
                            if (subInfo.Name != "已开单")
                            {
                                StartOrderBLL.OrderCtm oc = new StartOrderBLL.OrderCtm();
                                oc.CtmName = subInfo.Name + "2";                    //客户层，最后一位2表示处于第二层
                                oc.CtmText = subInfo.Name;
                                oc.CtmFullName = subInfo.FullName;
                                ot.Ctms.Add(oc);

                                string[] ssubFiles = GetFilesPath(subDirectory);
                                if (ssubFiles.Length > 0)                           //如果客户目录里有照片，就不再加载产品
                                    continue;
                                string[] ssubDirectorys = Directory.GetDirectories(subDirectory);
                                if (ssubDirectorys.Length == 0)                     //如果客户目录里没有子目录，就不再加载产品               
                                    continue;
                                foreach (string ssubDirectory in ssubDirectorys)
                                {
                                    if (IsEmpty(ssubDirectory, false))
                                        continue;
                                    DirectoryInfo ssubInfo = new DirectoryInfo(ssubDirectory);

                                    FileInfo[] sssfiles = GetFileInfo(ssubDirectory);
                                    DirectoryInfo[] sssdirectorys = ssubInfo.GetDirectories();
                                    if (sssfiles.Count() == 0 && sssdirectorys.Count() == 0)
                                        continue;
                                    StartOrderBLL.OrderProduct op = new StartOrderBLL.OrderProduct();
                                    op.ProductName = ssubInfo.Name + "3";           //产品层，最后一位3表示处于第三层
                                    op.ProductText = ssubInfo.Name;
                                    op.ProductFullName = ssubInfo.FullName;
                                    oc.Products.Add(op);

                                    foreach (DirectoryInfo sssDirectory in sssdirectorys)
                                    {
                                        StartOrderBLL.ProductCC cc = new StartOrderBLL.ProductCC();
                                        cc.CCName = sssDirectory.Name + "4";
                                        cc.CCText = sssDirectory.Name;
                                        cc.CCFullName = sssDirectory.FullName;
                                        op.Ccs.Add(cc);
                                    }
                                }
                            }
                        }
                    }
                }
                IsAddedOrderTree = true;                //表示已成功加载开单树
                FrmStartOrder.IsGetTree = true;
                FrmStartOrder.SetStartOrderTree(_startOrder);
                Thread.CurrentThread.Abort();           //加载完成终止线程
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                { }
            }
        }
        //指定的目录是否是空的
        public bool IsEmpty(string directory, bool isShop)
        {
            try
            {
                if (isShop == true)         //商户节点
                {
                    string[] subDirectorys = Directory.GetDirectories(directory);
                    if (subDirectorys.Length == 1)
                        return true;
                    else
                    {
                        foreach (string subDirectory in subDirectorys)
                        {
                            if (!IsEmpty(subDirectory, false))
                                return false;
                        }
                        return true;
                    }
                }
                else
                {

                    string[] subFiles = GetFilesPath(directory);
                    string[] subDirectorys = Directory.GetDirectories(directory);
                    if (subFiles.Length > 0)
                        return false;
                    foreach (string subDirectory in subDirectorys)
                    {
                        if (!IsEmpty(subDirectory, false))
                            return false;
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 调用刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _startOrder_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                cmbStatus.Text = "正常生产";
                cmbStatus_EditValueChanged(sender, e);
                //_controller.IsSearchedResult = false;
                //this.txtTotalPageCount.Text = _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text), OrderStatus).ToString();
                //ShowCount();
                this.gridControlOrders.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void barButtonSearch_ItemClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                _searchFrm = new FrmSearch(this._searchController);
                //_searchFrm.btnOK.Click += new EventHandler(btnOK_Click);
                //绑定查询结果处理方法
                _searchFrm._manage = this;
                _searchFrm.ShowDialog();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                throw ex;
            }
        }
        //处理查询的结果记录数
        public void btnOK_Click()
        {
            try
            {
                //当前模式设为查询模式
                _controller.IsSearchedResult = true;
                //设置基本数据(在查询模式下)
                SetBaseNum2();

                this.txtPageNumber.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
                SetFastSelect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void FrmManage_Load(object sender, EventArgs e)
        {
            try
            {
                //删除垃圾订单数据
                //userId = 35;                 //测试使用4
                _controller.DeleteTempOrder(userId);

                OrderStatus = (int)COM.OrderBagStatus.Doing;                                //默认取"正在生产"的订单
                _controller.Grid = this.gridControlOrders;
                _controller.GridCard = this.gridControlOrderDetail;

                _controller.View = this.gridViewOrder;
                //_controller.InitViewData(OrderStatus);


                _controller.ImageViewer = this.imageBagPic;

                _photoController.Grid = this.gridPhotoInfo;

                _flowController.Grid = this.gridControlWorkFlowList;
                _flowController.View = this.gridViewProductProcess;

                _talkRecordController.Grid = this.gridControlTalkRecord;
                _talkRecordController.Content = this.lookUpContent;

                //查询结果
                _searchController.Grid = this.gridControlOrders;

                this.gridViewOrder.Focus();

                //注册加急改变处理事件
                this.cmbPriority.EditValueChanged += new EventHandler(this.UpdatePriority);
                this.itemFetchTime.EditValueChanged += new EventHandler(this.UpdateFetchTime);



                //this.OrderReport.Preview = this.previewOrderBag;

                //设置订单总量，产品总量，当前页，总页数等基本信息
                SetBaseNum();

                this.tabControlDetail.TabPages.Remove(this.tabControlProduct);
                this.tabControlDetail.TabPages.Remove(this.tabPagePic);
                //操作员
                tsWorker.Text = userName;

                //停止恢复记录
                this._controller.GridStopRecord = gcStopRecord;

                //显示当前订单集合
                this.txtPageNumber.Text = _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(txtPageNumber.Text), OrderStatus).ToString();
                //设置快速筛选数据
                SetFastSelect();
                backgroundWorkerFindDely.WorkerReportsProgress = true;
                backgroundWorkerFindDely.WorkerSupportsCancellation = true;
                backgroundWorkerFindDely.RunWorkerAsync();

                //----------------------------------
                //----------另开线程移动照片--------
                //IsMovePhotoRun = false;             //移动照片的页面未运行
                //OpenMovePhoto();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

        }

        /// <summary>
        /// 设置快速筛选数据
        /// </summary>
        public void SetFastSelect()
        {
            _controller.SetFastSelectOrderCodeAndOrderName();
            //订单名称
            this.cmbOrderName.Properties.Items.Clear();
            foreach (string name in _controller.OrderNameList)
            {
                this.cmbOrderName.Properties.Items.Add(name);
            }
            //订单编码
            this.cmbOrderCode.Properties.Items.Clear();
            foreach (string code in _controller.CoedList)
            {
                this.cmbOrderCode.Properties.Items.Add(code);
            }
            //加急级别
            this.cmbPriority1.Properties.Items.Clear();
            List<int> ListPriority = _controller.GetCurrentPriority();
            foreach (int p in ListPriority)
            {
                this.cmbPriority1.Properties.Items.Add(p);
            }
            //设置快速筛选的当前流程节点
            //SetCurrentTechs();
        }

        //设置快速筛选的当前流程节点
        public void SetCurrentTechs()
        {
            try
            {
                this.cmbFlowList.Properties.DataSource = _controller.GetCurrentTechs();
                //this.cmbFlowList.ItemIndex = 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        #region //Relation

        private void gridViewOrder_MasterRowEmpty(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowEmptyEventArgs e)
        {
            e.IsEmpty = false;
        }

        private void gridViewOrder_MasterRowGetChildList(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetChildListEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                this._rowHandle = e.RowHandle;
                this._relationIndex = e.RelationIndex;
                OrderBagEntity obj = (OrderBagEntity)this.gridViewOrder.GetRow(e.RowHandle);

                if (obj != null)
                {
                    if (obj.StatusValue == (int)COM.OrderBagStatus.Completed)
                    {
                        e.ChildList = _infoController.GetOrderInfoByBagCode_bk(obj.OrderBagID);
                    }
                    else
                    {
                        e.ChildList = _infoController.GetOrderInfoByBagCode(obj.OrderBagID);
                    }
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void gridViewOrder_MasterRowGetRelationCount(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetRelationCountEventArgs e)
        {
            e.RelationCount = 1;
        }

        private void gridViewOrder_MasterRowGetRelationName(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetRelationNameEventArgs e)
        {
            e.RelationName = "产品";
        }


        #endregion

        private void gridViewOrder_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                this._focusOrderBag = this.gridViewOrder.GetFocusedRow() as OrderBagEntity;
                this._focusOrderInfo = null;

                this._rowHandle = e.RowHandle;

                if (_clickHandle != e.RowHandle)
                {
                    if (this.splitContainerControl2.PanelVisibility == SplitPanelVisibility.Both)
                    {
                    }
                }

                if (this.tabControlDetail.TabPages.Count > 3)
                {
                    this.tabControlDetail.TabPages.Remove(this.tabControlProduct);
                    this.tabControlDetail.TabPages.Remove(this.tabPagePic);
                    this.tabControlDetail.TabPages.Remove(this.tabStopRecord);
                    this.tabControlDetail.TabPages.Remove(this.pageReOrderRecoder);
                }
                //清空流程列表
                _flowController.SetEmptyFlow();
                _controller.GetOrderBagDetail(sender, e.RowHandle);
                //_controller.GetDefaultBagImage();
                //_talkRecordController.GetTalkRecordListByOrderBag(sender);
                //防止多次加载文件

                _clickHandle = e.RowHandle;
                if (this._focusOrderBag.Status.Equals("已删除"))
                {
                    tsCheckAutoStartOrder.Enabled = false;
                    btnCheckOrder.Enabled = false;
                    tsDelOrder.Enabled = false;
                    toolStopItem.Enabled = false;
                    toolRecordItem.Enabled = false;
                }
                else
                {
                    tsCheckAutoStartOrder.Enabled = true;
                    btnCheckOrder.Enabled = true;
                    tsDelOrder.Enabled = true;
                    toolStopItem.Enabled = true;
                    toolRecordItem.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

        }

        private void gridViewOrder_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle < 0)
                    return;
                this._focusOrderBag = this.gridViewOrder.GetFocusedRow() as OrderBagEntity;
                this._focusOrderInfo = null;

                this._rowHandle = e.FocusedRowHandle;

                if (_clickHandle != e.FocusedRowHandle)
                {
                    if (this.splitContainerControl2.PanelVisibility == SplitPanelVisibility.Both)
                    {
                    }
                }

                if (this.tabControlDetail.TabPages.Count > 3)
                {
                    this.tabControlDetail.TabPages.Remove(this.tabControlProduct);
                    this.tabControlDetail.TabPages.Remove(this.tabPagePic);
                    this.tabControlDetail.TabPages.Remove(this.tabStopRecord);
                }
                //清空流程列表
                _flowController.SetEmptyFlow();
                //_controller.GetOrderBagDetail(sender, e.FocusedRowHandle);
                //_controller.GetDefaultBagImage();
                //_talkRecordController.GetTalkRecordListByOrderBag(sender);
                //防止多次加载文件

                _clickHandle = e.FocusedRowHandle;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        /// <summary>
        /// 当点击产品行时处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridViewProduct_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                _infoController.FocusView = view;
                OrderInfoEntity item = view.GetFocusedRow() as OrderInfoEntity;
                this._focusOrderInfo = item;
                if (this.tabControlDetail.TabPages.Count < 4)
                {
                    this.tabControlDetail.TabPages.Add(this.tabControlProduct);
                    this.tabControlDetail.TabPages.Add(this.tabPagePic);
                    this.tabControlDetail.TabPages.Add(this.tabStopRecord);
                    this.tabControlDetail.TabPages.Add(this.pageReOrderRecoder);
                }
                this._orderProductID = item.OrderProductId;
                DevExpress.XtraTab.XtraTabPage currentPage = tabControlDetail.SelectedTabPage;
                if (item.Status.Equals("已删除"))
                {
                    tsCheckAutoStartOrder.Enabled = false;
                    btnCheckOrder.Enabled = false;
                    tsDelOrder.Enabled = false;
                    toolStopItem.Enabled = false;
                    toolRecordItem.Enabled = false;
                }
                else
                {
                    tsCheckAutoStartOrder.Enabled = true;
                    btnCheckOrder.Enabled = true;
                    tsDelOrder.Enabled = true;
                    toolStopItem.Enabled = true;
                    toolRecordItem.Enabled = true;
                }


                if (currentPage.Name == "tabControlProduct")                //加载产品流程
                {
                    _flowController.GetFlowList(sender, e, this._focusOrderBag.StatusValue);
                }
                else if (currentPage.Name == "tabPagePic")               //加载缩略图   
                {
                    _photoController.LblPhotoCountC = lblPhotoCountC;
                    _photoController.SetGridData(item.OrderProductId, this._focusOrderBag.StatusValue);
                    currentStyleProduct = _controller.GetStyleProduct(item.OrderProductId, this._focusOrderBag.StatusValue);
                }
                else if (currentPage.Name == "tabStopRecord")       //加载停止、恢复记录
                {
                    if (item != null)
                    {
                        this._orderProductID = item.OrderProductId;
                        _photoController.SetGridData(item.OrderProductId, this._focusOrderBag.StatusValue);
                        this.lblPhotoCountC.Text = _photoController.PhotoCount.ToString();

                        //停止、恢复产品记录
                        _controller.GridStopRecord = gcStopRecord;
                        _controller.SetStopRecord(item.OrderProductId);
                    }
                    else
                    {
                        this._orderProductID = 0;
                        _photoController.SetGridData(0, this._focusOrderBag.StatusValue);
                    }

                }
                else if (currentPage.Name == "pageReOrderRecoder")
                {
                    if (item != null)
                    {
                        //加载返单记录
                        DataTable dt = _controller.GetReBackOrderReCord(item);

                        gcRebackRecord.DataSource = dt;

                    }
                }
                else                                                    //其余情况不加载任何内容
                {
                    return;
                }

                /*
                _flowController.GetFlowList(sender, e);
                if (item != null)
                {
                    this._orderProductID = item.OrderProductId;
                    _photoController.SetGridData(item.OrderProductId);
                    this.lblPhotoCountC.Text = _photoController.PhotoCount.ToString();
                }
                else
                {
                    this._orderProductID = 0;
                    _photoController.SetGridData(0);
                }
                 * */
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void gridViewOrder_RowStyle(object sender, RowStyleEventArgs e)
        {
            //_controller.SetBackColor(e);
            e.Appearance.BackColor = Color.Orange;
            e.Appearance.BackColor2 = Color.Orange;

            //显示报警色
            //_controller.CheckAlarm(e);
        }

        private void gridViewProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            //_infoController.SetSubBackColor(e);正常情况下产品无背景色
            //显示报警色
            _infoController.CheckAlarm(sender, e);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (_talkRecordController.Check(this.txtContents.Text))
                    _talkRecordController.AddRecord(this.userId, this.txtContents.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        /// <summary>
        /// 编辑行操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonEdit_ItemClick(object sender, EventArgs e)
        {
            if (this.gridViewOrder.IsFocusedView)
            {
                if (_controller.CheckUsed())
                {
                    _controller.UpdateEditStatus();
                }
            }
            else
            {
                if (_infoController.CheckUsed())
                {
                    _infoController.UpdateEditStatus();
                }
            }

        }


        /// <summary>
        /// 设置有焦点的产品明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridViewProduct_GotFocus(object sender, EventArgs e)
        {


        }
        private void gridViewProduct_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            //指定当前选择的VIEW
            try
            {
                if (e.FocusedRowHandle < 0)
                    return;
                GridView view = sender as GridView;
                OrderInfoEntity item = view.GetFocusedRow() as OrderInfoEntity;
                if (item == null)
                    return;
                _infoController.FocusView = view;
                _flowController.SetCurrentFlowList(item, this._focusOrderBag.StatusValue);
                if (this.tabControlDetail.TabPages.Count < 4)
                {
                    this.tabControlDetail.TabPages.Add(this.tabControlProduct);
                    this.tabControlDetail.TabPages.Add(this.tabPagePic);
                    this.tabControlDetail.TabPages.Add(tabStopRecord);
                }

                this._orderProductID = item.OrderProductId;
                DevExpress.XtraTab.XtraTabPage currentPage = tabControlDetail.SelectedTabPage;

                if (currentPage.Name == "tabControlProduct")                //加载产品流程
                {
                    _flowController.SetCurrentFlowList(item, this._focusOrderBag.StatusValue);
                }
                else if (currentPage.Name == "tabPagePic")               //加载缩略图   
                {
                    _photoController.LblPhotoCountC = lblPhotoCountC;
                    _photoController.SetGridData(item.OrderProductId, this._focusOrderBag.StatusValue);
                }
                else if (currentPage.Name == "tabStopRecord")       //加载停止、恢复记录
                {
                    if (item != null)
                    {
                        this._orderProductID = item.OrderProductId;
                        _photoController.SetGridData(item.OrderProductId, this._focusOrderBag.StatusValue);
                        this.lblPhotoCountC.Text = _photoController.PhotoCount.ToString();

                        //停止、恢复产品记录
                        _controller.GridStopRecord = gcStopRecord;
                        _controller.SetStopRecord(item.OrderProductId);
                    }
                    else
                    {
                        this._orderProductID = 0;
                        _photoController.SetGridData(0, this._focusOrderBag.StatusValue);
                    }

                }
                else                                                    //其余情况不加载任何内容
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        /// <summary>
        /// 调整工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPre_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 调整工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            _flowController.NextRecord();
        }


        #region  //组合快速查询

        private void cmbOrderName_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
            ShowCount();
        }

        private void cmbOrderCode_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
            ShowCount();
        }

        private void dtOrderStart_EditValueChanged(object sender, EventArgs e)
        {
            if (dtOrderStart.DateTime == DateTime.MinValue)
            {
                dtOrderStart.EditValue = null;
            }

            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
            ShowCount();
        }

        private void dtOrderEnd_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
            ShowCount();
        }

        private void cmbPriority1_EditValueChanged(object sender, EventArgs e)
        {

            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();

            ShowCount();
        }

        private void dtFetchStart_EditValueChanged(object sender, EventArgs e)
        {
            if (dtFetchStart.DateTime == DateTime.MinValue)
            {
                dtFetchStart.EditValue = null;
            }
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();

            ShowCount();
        }

        private void dtFetchEnd_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();

            ShowCount();
        }

        //当订单状态发生改变时，默认取设置的条数
        private void cmbStatus_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                //当前模式设为普通模式
                _controller.IsSearchedResult = false;
                string statusStr = cmbStatus.Text;
                switch (statusStr)
                {
                    case "移动照片":
                        OrderStatus = (int)COM.OrderBagStatus.WaitPhotoMove; break;
                    case "正常生产":
                        OrderStatus = (int)COM.OrderBagStatus.Doing; break;
                    case "生产完成":
                        OrderStatus = (int)COM.OrderBagStatus.Completed; break;
                    case "有产品暂停":
                        OrderStatus = (int)COM.OrderBagStatus.ProductStop; break;
                    case "暂停生产":
                        OrderStatus = (int)COM.OrderBagStatus.OrderBagStop; break;
                    case "未生产":
                        OrderStatus = (int)COM.OrderBagStatus.UnComplete; break;        //好像不准确
                    case "错误":
                        OrderStatus = (int)COM.OrderBagStatus.Eroor; break;
                    case "全部":
                        OrderStatus = -1; break;
                    case "已删除":
                        OrderStatus = (int)COM.OrderBagStatus.Deleted; break;
                    case "财务审核":
                        OrderStatus = (int)OrderBagStatus.WaitPay;
                        break;
                    default:
                        OrderStatus = (int)COM.OrderBagStatus.Doing; break;              //默认显示"正常生产"的订单
                }

                //设置订单总量，产品总量，当前页，总页数等基本信息
                SetBaseNum();

                int currentPage = _controller.PageCountChanged(Convert.ToInt32(cmbPageCount.Text), Convert.ToInt32(txtPageNumber.Text), OrderStatus);
                txtPageNumber.Text = currentPage.ToString();

                //设置快速筛选数据
                _controller.SetFastSelectOrderCodeAndOrderName();
                SetFastSelect();
                ShowCount();

                //清空快速筛选的条件
                ClearFastFind();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 设置订单总量，产品总量，当前页，总页数等基本信息
        /// </summary>
        public void SetBaseNum()
        {
            try
            {
                //获取当前状态下订单总量
                _controller.GetTotalOrderNum(OrderStatus);
                //显示数量
                ShowCount();

                int pageCount = int.Parse(this.cmbPageCount.EditValue.ToString());
                if (_controller.OrderBagCount % pageCount != 0)
                {
                    this.txtTotalPageCount.Text = ((_controller.OrderBagCount / pageCount) + 1).ToString();
                }
                else
                {
                    this.txtTotalPageCount.Text = (_controller.OrderBagCount / pageCount).ToString();
                }
                if (this.txtPageNumber.Text == "")
                    this.txtPageNumber.Text = "1";  //默认取第1页
                else
                {
                    int oldPage = Convert.ToInt32(this.txtPageNumber.Text);
                    if (oldPage > Convert.ToInt32(this.txtTotalPageCount.Text))
                        this.txtPageNumber.Text = this.txtTotalPageCount.Text;
                }
                if (this.txtPageNumber.Text == "0")
                    this.txtPageNumber.Text = "1";
                if (this.txtTotalPageCount.Text == "0")
                    this.txtTotalPageCount.Text = "1";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 设置订单总量，产品总量，当前页，总页数等基本信息(处于查询模式下)
        /// </summary>
        public void SetBaseNum2()
        {
            try
            {
                //获取当前状态下订单总量
                _controller.GetTotalOrderNum();
                //显示数量
                ShowCount();

                int pageCount = int.Parse(this.cmbPageCount.EditValue.ToString());
                if (_controller.OrderBagCount % pageCount != 0)
                {
                    this.txtTotalPageCount.Text = (_controller.OrderBagCount / pageCount + 1).ToString();
                }
                else
                {
                    int t = _controller.OrderBagCount / pageCount;
                    if (t == 0)
                        this.txtTotalPageCount.Text = "1";
                    else
                        this.txtTotalPageCount.Text = (_controller.OrderBagCount / pageCount).ToString();
                }

                if (this.txtPageNumber.Text == "")
                    this.txtPageNumber.Text = "1";
                else
                {
                    int oldPage = Convert.ToInt32(this.txtPageNumber.Text);
                    if (oldPage > Convert.ToInt32(this.txtTotalPageCount.Text))
                        this.txtPageNumber.Text = this.txtTotalPageCount.Text;
                }
                if (this.txtPageNumber.Text == "0")
                    this.txtPageNumber.Text = "1";
                if (this.txtTotalPageCount.Text == "0")
                    this.txtTotalPageCount.Text = "1";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void cmbFlowList_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();

            ShowCount();
        }

        private void cmbOperator_EditValueChanged(object sender, EventArgs e)
        {
            ComCondtion();
            _controller.RapidSearch(_condition);
            if (_controller.IsSearchedResult)
                this.txtTotalPageCount.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
            ShowCount();
        }

        #endregion

        //显示记录的数量
        private void ShowCount()
        {
            this.lblCount.Text = _controller.ProductCount.ToString();
            this.lblOrderBagCount.Text = _controller.OrderBagCount.ToString();

            int pageCount = int.Parse(this.cmbPageCount.Text);
            int t = _controller.OrderBagCount % pageCount == 0 ? _controller.OrderBagCount / pageCount : (_controller.OrderBagCount / pageCount + 1);
            this.txtTotalPageCount.Text = t.ToString();
        }

        #region //组合查询条件

        /// <summary>
        /// 根据输入组合查询条件
        /// </summary>
        private void ComCondtion()
        {
            _condition.bagName = string.Empty;
            _condition.bagCode = string.Empty;
            _condition.priority = -1;
            //_condition.status = -1;
            _condition.orderStart = DateTime.MinValue;
            _condition.orderEnd = DateTime.MinValue;
            _condition.fetchStart = DateTime.MinValue;
            _condition.fetchEnd = DateTime.MinValue;

            if (string.Compare(cmbOrderName.Text, string.Empty) != 0)
            {
                _condition.bagName = cmbOrderName.Text;
            }

            if (string.Compare(cmbOrderCode.Text, string.Empty) != 0)
            {
                _condition.bagCode = cmbOrderCode.Text;
            }

            if (this.cmbPriority1.EditValue != null && this.cmbPriority1.EditValue.ToString() != string.Empty)
            {
                _condition.priority = int.Parse(this.cmbPriority1.EditValue.ToString());
            }

            //订单状态不再在普通筛选中使用
            /*if (!string.IsNullOrEmpty(this.cmbStatus.Text) && this.cmbStatus.Text != "全部")
            {
                string statusStr = this.cmbStatus.Text;
                int status = -1;
                switch (statusStr)
                {
                    case "正常生产":
                        status = (int)COM.OrderBagStatus.Doing; break;
                    case "生产完成":
                        status = (int)COM.OrderBagStatus.Completed; break;
                    case "暂停生产":
                        status = (int)COM.OrderBagStatus.OrderBagStop; break;
                    case "未生产":
                        status = (int)COM.OrderBagStatus.UnComplete; break;
                    case "错误":
                        status = (int)COM.OrderBagStatus.Eroor; break;

                }
                //_condition.status = this.cmbStatus.SelectedIndex + 1;
                _condition.status = status;
            }*/

            _condition.orderStart = dtOrderStart.DateTime;
            if (_condition.orderStart != DateTime.MinValue)
                _condition.orderEnd = dtOrderStart.DateTime.Date.AddDays(1);
            _condition.fetchStart = dtFetchStart.DateTime;
            if (_condition.fetchStart != DateTime.MinValue)
                _condition.fetchEnd = dtFetchStart.DateTime.Date.AddDays(1);
            if (cmbFlowList.EditValue != null)
            {
                _condition.flowList = (int)cmbFlowList.EditValue;
            }
            if (cmbOperator.EditValue != null)
            {
                _condition.userID = (int)cmbOperator.EditValue;
            }
        }

        #endregion

        private void FrmManage_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (MessageBox.Show("确定退出客服？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                {
                    //关闭移动照片窗体
                    //CloseMP c = new CloseMP(CloseMovePhoto);
                    //this.Invoke(c);

                    int mainFrm = (int)Logoff.FindWindow(null, "用户选择");
                    if (mainFrm > 0)
                    {
                        Logoff.ShowMainFrm();   //激活用户选择窗体

                        this.Dispose(true);
                        this.Close();
                    }
                }
                else
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 更新加急级别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdatePriority(object sender, EventArgs e)
        {
            try
            {
                ComboBoxEdit comEdit = (ComboBoxEdit)sender;

                _controller.Update(int.Parse(comEdit.EditValue.ToString()));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }
        /// <summary>
        /// 更新取件时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateFetchTime(object sender, EventArgs e)
        {
            try
            {
                DateEdit dateEdit = (DateEdit)sender;
                _controller.Update(dateEdit.DateTime);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtContents.Text = string.Empty;
        }

        private void gridViewOrder_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void barButtonRecover_ItemClick(object sender, EventArgs e)
        {
            try
            {
                if (this._focusOrderInfo == null)
                {
                    OrderBagEntity bagItem = this.gridViewOrder.GetFocusedRow() as OrderBagEntity;
                    if (bagItem != null)
                    {
                        if (bagItem.StatusValue == (int)OrderBagStatus.OrderBagStop || bagItem.StatusValue == (int)OrderBagStatus.ProductStop)
                        {
                            if (MessageBox.Show("确定要恢复改订单成产", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                            {
                                FrmStopRemark frm = new FrmStopRemark();
                                frm.fm = this;
                                if (DialogResult.OK != frm.ShowDialog())
                                {
                                    return;

                                }
                                this.Cursor = Cursors.WaitCursor;
                                _controller.InsertStopOrRecorverRemark(bagItem.OrderBagID, 1, StopRemark, userId);
 
                            }
                        }
                    }

                }
                else
                {

                    //_focusOrderInfo = gridViewProduct.GetFocusedRow() as OrderInfoEntity;
                    _focusOrderInfo = ((GridView)(gridControlOrders.FocusedView)).GetFocusedRow() as OrderInfoEntity;
                    if (this._focusOrderInfo != null)
                    {

                        int orderInfoStatus = _controller.GetOrderInfoStatus(this._focusOrderInfo.OrderProductId);
                        if (orderInfoStatus != (int)OrderInfoStatus.Stop)
                        {
                            MessageBox.Show("产品并未停止生产", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        if (MessageBox.Show("确定恢复该产品的生产？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {
                            //输入停止订单生产的原因
                            FrmStopRemark fsr = new FrmStopRemark();
                            fsr.fm = this;
                            if (DialogResult.OK != fsr.ShowDialog())
                                return;
                            Cursor = Cursors.WaitCursor;

                            //恢复流程的生产状态更新数据库的操作
                            _controller.InsertStopOrRecorverRemark2(this._focusOrderInfo.OrderProductId, 1, StopRemark, userId);        //插入恢复产品生产的备注

                            //刷新停止记录列表
                            _controller.SetStopRecord(this._focusOrderInfo.OrderProductId);

                            gridControlOrders.RefreshDataSource();
                            barButtonItem1_ItemClick(sender, e);
                            Cursor = Cursors.Default;
                        }
                    }


                }
                this.gridViewOrder.SetMasterRowExpandedEx(_rowHandle, _relationIndex, false);
                this.gridViewOrder.SetMasterRowExpandedEx(_rowHandle, _relationIndex, true);

                this.gridViewOrder.RefreshData();
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }
        /// <summary>
        /// 刷新显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                //删除垃圾订单数据
                //_controller.DeleteTempOrder(userId);

                _controller.IsSearchedResult = false;
                //设置基本数据
                SetBaseNum();
                _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text), OrderStatus);
                //设置快速晒选数据
                _controller.SetFastSelectOrderCodeAndOrderName();
                SetFastSelect();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void barButtonItemAddProduct_ItemClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (this.gridViewOrder.SelectedRowsCount > 0)
                {

                    OrderBagEntity item = (OrderBagEntity)this.gridViewOrder.GetFocusedRow();
                    if (item.Status.Equals("已完成"))
                    {
                        MessageBox.Show("已完成的订单不能编辑", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        return;
                    }
                    //if (item.IsEdit != 0 && this.userId != item.IsEdit)
                    //{
                    //    MessageBox.Show("此订单正在编辑，请选择其他订单.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    //    return;
                    //}

                    if (EditOrderNum > 0)
                    {
                        Cursor = Cursors.Default;
                        return;
                    }
                    EditOrderNum++;
                    //更新订单为正在编辑状态
                    item.IsEdit = this.userId;
                    _controller.UpdateEditStatus();

                    int orderInfoId = this._orderProductID;

                    _editOrder = new FrmEditOrder(item.OrderBagID, orderInfoId);
                    _editOrder.Manage = this;
                    _editOrder.UserType = 1;            //表示是普通的编辑调用
                    _editOrder.EditUserId = userId;
                    //添加更新处理程序
                    //_editOrder.FormClosed += new FormClosedEventHandler(_editOrder_FormClosed);
                    _editOrder.ShowDialog();
                }
                else
                {
                    MessageBox.Show("请先选择订单", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        private void _editOrder_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                this.gridViewOrder.SetMasterRowExpandedEx(_rowHandle, _relationIndex, false);
                this.gridViewOrder.SetMasterRowExpandedEx(_rowHandle, _relationIndex, true);

                //更新订单的状态为可编辑状态
                OrderBagEntity item = this.gridViewOrder.GetRow(_clickHandle) as OrderBagEntity;
                item.IsEdit = this.userId;
                _controller.UpdateEditStatus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        /// <summary>
        /// 缩略图和列表的切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPhotoSwitch_Click(object sender, EventArgs e)
        {
            try
            {
                if (this._isPhotoMode)
                {
                    this.panelControl1.Controls.Clear();
                    this.panelControl1.Controls.Add(this.gridPhotoInfo);
                    this._isPhotoMode = false;
                    this._photoController.SetGridData(this._focusOrderInfo.OrderProductId, this._focusOrderBag.StatusValue);
                }
                else
                {
                    this._isPhotoMode = true;

                    RasterThumbnailBrowser photoBrowser = new RasterThumbnailBrowser();
                    photoBrowser.DoubleClick += new EventHandler(photoBrowser_DoubleClick);

                    this.panelControl1.Controls.Clear();
                    this.panelControl1.Controls.Add(photoBrowser);

                    this._infoController.ImagerBrowser = photoBrowser;
                    photoBrowser.Dock = DockStyle.Fill;
                    //this._infoController.GetImageList(this._focusOrderInfo.OrderProductId);
                    List<BLL.CustomerManage.PhotoInfoEntity> photos = gridPhotoInfo.DataSource as List<BLL.CustomerManage.PhotoInfoEntity>;
                    List<string> photoPaths = new List<string>();
                    foreach (BLL.CustomerManage.PhotoInfoEntity photo in photos)
                    {
                        photoPaths.Add(photo.picPath);
                        photoPaths.Add(photo.PhotoBarCode);
                    }
                    this._infoController.GetImageList(photoPaths);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        //双击缩略图，显示其原图
        void photoBrowser_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                RasterThumbnailBrowser b = sender as RasterThumbnailBrowser;
                string selectedPath = b.SelectedItems[0].Tag.ToString();
                //浏览大图
                List<string> photoPaths = new List<string>();
                int currentIndex = 0;
                foreach (RasterImageListItem item in b.Items)
                {
                    photoPaths.Add(item.Tag.ToString());
                    photoPaths.Add(item.Text);
                }
                for (int i = 0; 2 * i < photoPaths.Count; i++)
                {
                    if (selectedPath == photoPaths[2 * i])
                    {
                        currentIndex = i;
                        break;
                    }
                }
                ComControls.BigPicViewer bpv = new BigPicViewer();
                bpv.PhotoPaths = photoPaths;
                bpv.CurrentIndex = currentIndex;
                bpv.ShowDialog();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void gridViewProductProcess_RowStyle(object sender, RowStyleEventArgs e)
        {
            _flowController.CheckAlarm(e);
        }

        /// <summary>
        /// 取消产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonDelete_ItemClick(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("您确定要暂停生产该产品吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                try
                {
                    //_focusOrderInfo = gridViewProduct.GetFocusedRow() as OrderInfoEntity;
                    _focusOrderInfo = ((GridView)(gridControlOrders.FocusedView)).GetFocusedRow() as OrderInfoEntity;

                    if (this._focusOrderInfo != null)
                    {
                        bool IsMakeBigBoardOK = _controller.MakeBigBoardOK(_focusOrderInfo.OrderProductId);
                        if (IsMakeBigBoardOK)
                        {
                            MessageBox.Show("产品中有照片已经排板，请找输出部门退板后再停止！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }

                        int orderInfoStatus = _controller.GetOrderInfoStatus(this._focusOrderInfo.OrderProductId);
                        if (orderInfoStatus == (int)OrderInfoStatus.Stop)
                        {
                            MessageBox.Show("产品已经停止生产", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        if (orderInfoStatus == (int)OrderInfoStatus.Completed)
                        {
                            MessageBox.Show("产品已完成，不能停止生产", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        if (MessageBox.Show("确定停止该产品的生产？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                        {

                            FrmStopRemark fsr = new FrmStopRemark();
                            fsr.fm = this;
                            if (DialogResult.OK != fsr.ShowDialog())
                                return;
                            Cursor = Cursors.WaitCursor;

                            _controller.InsertStopOrRecorverRemark2(this._focusOrderInfo.OrderProductId, 0, StopRemark, userId);    //保存停止产品的备注

                            //刷新停止记录列表
                            _controller.SetStopRecord(this._focusOrderInfo.OrderProductId);
                            //控件刷新

                            gridControlOrders.RefreshDataSource();
                            barButtonItem1_ItemClick(sender, e);
                            Cursor = Cursors.Default;

                        }
                    }
                    this.gridViewOrder.SetMasterRowExpandedEx(_clickHandle, _relationIndex, false);
                    this.gridViewOrder.SetMasterRowExpandedEx(_clickHandle, _relationIndex, true);

                    this.gridViewOrder.RefreshData();
                }
                catch (Exception ex)
                {
                    Cursor = Cursors.Default;
                    MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }
            }
        }

        /// <summary>
        /// 导出功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_ItemClick(object sender, EventArgs e)
        {
            //saveExportDialog.Filter = "文本文件 (*.txt)|*.txt|pdf(*.pdf)|*.pdf|电子表格(*.xls)|*.xls|html(*.html)|*.html";
            //saveExportDialog.FilterIndex = 3;
            //saveExportDialog.RestoreDirectory = true;

            //this.gridViewOrder.OptionsPrint.PrintDetails = true;
            //this.gridViewOrder.OptionsPrint.ExpandAllDetails = true;
            //this.gridViewOrder.OptionsPrint.ExpandAllGroups = true;
            try
            {
                //string fileName = this.saveExportDialog.FileName;
                gridControlOrders.ExportToExcel(this, "客服订单信息");
                //if (this.saveExportDialog.ShowDialog() == DialogResult.OK)
                //{
                //    string fileName = this.saveExportDialog.FileName;

                //    if (saveExportDialog.OpenFile() != null)
                //    {
                //        switch (this.saveExportDialog.FilterIndex)
                //        {
                //            case 3:
                //                this.gridViewOrder.ExportToXls(fileName);
                //                return;
                //            case 4:
                //                this.gridViewOrder.ExportToHtml(fileName);
                //                return;
                //            case 2:
                //                this.gridViewOrder.ExportToPdf(fileName);
                //                return;
                //            case 1:
                //                this.gridViewOrder.ExportToText(fileName);
                //                return;
                //        }
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        //根据焦点所在的订单行，设置该订单的明细

        /// <summary>
        /// 展开伸缩功能(已将其删除)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*
        private void btnExpand_Click(object sender, EventArgs e)
        {
            try
            {
                if (toolExpand.Text == "展开")
                {
                    toolExpand.Text = "折叠";

                    this.Cursor = Cursors.WaitCursor;

                    for (int i = 0; i < this.gridViewOrder.RowCount; i++)
                    {
                        this.gridViewOrder.ExpandMasterRow(i);
                    }
                    this.Cursor = Cursors.Default;
                }
                else
                {
                    this.Cursor = Cursors.WaitCursor;

                    toolExpand.Text = "展开";
                    this.gridViewOrder.CollapseAllDetails();
                    this.Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }*/

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbPageCount_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (_controller.IsSearchedResult)
                {
                    this.txtPageNumber.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
                }
                else
                {
                    this.txtPageNumber.Text = _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text), OrderStatus).ToString();
                }
                int t = (_controller.OrderBagCount % int.Parse(cmbPageCount.EditValue.ToString())) == 0 ? (_controller.OrderBagCount / int.Parse(cmbPageCount.EditValue.ToString())) : (_controller.OrderBagCount / int.Parse(cmbPageCount.EditValue.ToString()) + 1);
                this.txtTotalPageCount.Text = t.ToString();//总页数
                //设置快速筛选数据
                SetFastSelect();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPageNumber_EditValueChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 上一页
        /// </summary>
        private void btnPrePage_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            int currentPage = 1;
            try
            {
                currentPage = int.Parse(this.txtPageNumber.Text);
            }
            catch (Exception)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("请输入数字！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (currentPage == 1)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("已经是第一页", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (_controller.IsSearchedResult)
                {
                    _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), currentPage - 1);
                }
                else
                {
                    _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), currentPage - 1, OrderStatus);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            this.txtPageNumber.Text = (currentPage - 1).ToString();
            //设置快速筛选数据
            SetFastSelect();
            Cursor = Cursors.Default;
        }

        /// <summary>
        /// 下一页
        /// </summary>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            int currentPage = 1;
            try
            {
                currentPage = int.Parse(this.txtPageNumber.Text);
            }
            catch (Exception)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("请输入数字！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int lastPage = int.Parse(this.txtTotalPageCount.Text);
            if (currentPage == lastPage)
            {
                Cursor = Cursors.Default;
                MessageBox.Show("已经是最后一页", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (_controller.IsSearchedResult)
                {
                    _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), currentPage + 1);
                }
                else
                {
                    _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), currentPage + 1, OrderStatus);
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            //设置快速筛选数据
            SetFastSelect();
            this.txtPageNumber.Text = (currentPage + 1).ToString();
            Cursor = Cursors.Default;
        }

        //private void dtOrderStart_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        //{
        //    this.dtOrderStart.ClosePopup();
        //}

        //private void dtFetchStart_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        //{
        //    this.dtFetchStart.ClosePopup();
        //}

        /// <summary>
        /// 开单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolAddItem_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (StartOrderNum > 0)
                {
                    Cursor = Cursors.Default;
                    return;
                }
                StartOrderNum++;
                _startOrder = new FrmStartOrder();
                _startOrder.UserID = this.userId;
                _startOrder.UserName = this.userName;
                _startOrder.Manage = this;

                Cursor = Cursors.Default;

                //绑定刷新处理功能(关闭开单页面后默认不刷新)
                //_startOrder.FormClosed += new FormClosedEventHandler(_startOrder_FormClosed);
                _startOrder.Show();
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }


        /// <summary>
        /// 双击打开和关闭组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridViewOrder_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (this.gridViewOrder.GetMasterRowExpanded(_clickHandle))
                {
                    this.gridViewOrder.CollapseMasterRow(_clickHandle);
                }
                else
                {
                    this.gridViewOrder.ExpandMasterRow(_clickHandle);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        private void cmbOrderCode_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //当前页只能输入数字
        private void txtPageNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnPage_Click(sender, e);
            }
        }

        //编辑取件时间，加急级别
        private void gridViewOrder_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                switch (e.Column.Caption)
                {
                    case "加急级别":
                        _controller.UpdatePriority(((OrderBagEntity)gridViewOrder.GetRow(e.RowHandle)).OrderBagID, Convert.ToInt16(e.Value));
                        gridControlOrders.RefreshDataSource();
                        break;
                    case "完成时间":    //暂时不作处理 
                        UpdateCompleteTime(((OrderBagEntity)gridViewOrder.GetRow(e.RowHandle)).OrderBagID, Convert.ToDateTime(e.Value)); break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// 更新指定订单的完成时间(暂时不修改)
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="completeTime"></param>
        private void UpdateCompleteTime(int orderId, DateTime completeTime)
        {

        }

        /// <summary>
        /// 产品详情的显示部分发生改变时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControlDetail_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            DevExpress.XtraTab.XtraTabPage currentPage = tabControlDetail.SelectedTabPage;

            if (currentPage.Name == "tabControlProduct")                //加载产品流程
            {
                _flowController.SetCurrentFlowList(_focusOrderInfo, this._focusOrderBag.StatusValue);
            }
            else if (currentPage.Name == "tabPagePic")               //加载缩略图   
            {
                if (this._isPhotoMode)
                {
                    this.panelControl1.Controls.Clear();
                    this.panelControl1.Controls.Add(this.gridPhotoInfo);
                    this._isPhotoMode = false;
                    this._photoController.SetGridData(this._focusOrderInfo.OrderProductId, this._focusOrderBag.StatusValue);
                }

                if (_focusOrderInfo != null)
                {
                    this._orderProductID = _focusOrderInfo.OrderProductId;

                    _photoController.LblPhotoCountC = lblPhotoCountC;
                    _photoController.SetGridData(_focusOrderInfo.OrderProductId, this._focusOrderBag.StatusValue);
                    currentStyleProduct = _controller.GetStyleProduct(_focusOrderInfo.OrderProductId, this._focusOrderBag.StatusValue);
                }
                else
                {
                    this._orderProductID = 0;
                    _photoController.LblPhotoCountC = lblPhotoCountC;
                    _photoController.SetGridData(0, this._focusOrderBag.StatusValue);
                    currentStyleProduct = _controller.GetStyleProduct(_orderProductID, this._focusOrderBag.StatusValue);
                }
            }
            else if (currentPage.Name == "tabStopRecord")       //加载停止、恢复记录
            {
                if (_focusOrderInfo != null)
                {
                    this._orderProductID = _focusOrderInfo.OrderProductId;
                    _photoController.SetGridData(_focusOrderInfo.OrderProductId, this._focusOrderBag.StatusValue);
                    this.lblPhotoCountC.Text = _photoController.PhotoCount.ToString();

                    //停止、恢复产品记录
                    _controller.GridStopRecord = gcStopRecord;
                    _controller.SetStopRecord(_focusOrderInfo.OrderProductId);
                }
                else
                {
                    this._orderProductID = 0;
                    _photoController.SetGridData(0, this._focusOrderBag.StatusValue);
                }

            }
            else                                                    //其余情况不加载任何内容
            {
                return;
            }
        }

        //单击转到指定页
        private void btnPage_Click(object sender, EventArgs e)
        {
            try
            {
                //判断输入的当前页是否符合要求
                try
                {
                    Cursor = Cursors.WaitCursor;
                    int page = Convert.ToInt32(this.txtPageNumber.Text);
                    if (page == 0)
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show("当前页码不能为0", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtPageNumber.SelectAll();
                        this.txtPageNumber.Focus();
                        return;
                    }
                }
                catch
                {
                    Cursor = Cursors.Default;
                    MessageBox.Show("页码的格式不正确", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtPageNumber.SelectAll();
                    this.txtPageNumber.Focus();
                    return;
                }
                if (_controller.IsSearchedResult)
                {
                    this.txtPageNumber.Text = _controller.SearchResultPageChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text)).ToString();
                }
                else
                {
                    this.txtPageNumber.Text = _controller.PageCountChanged(int.Parse(cmbPageCount.EditValue.ToString()), int.Parse(this.txtPageNumber.Text), OrderStatus).ToString();
                }
                //设置快速筛选的数据
                SetFastSelect();
                int cpage = Convert.ToInt32(txtPageNumber.Text);
                int totalPage = Convert.ToInt32(txtTotalPageCount.Text);
                if (cpage > totalPage)
                    txtPageNumber.Text = totalPage.ToString();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
        }

        //----------------------------------------------------------------------------
        //---------------------------另开线程打开移动照片页面-------------------------
        delegate void CloseMP();

        public void OpenMovePhoto()
        {
            if (IsMovePhotoRun == false)
            {
                IsMovePhotoRun = true;                  //移动照片的页面已在运行
                fpm = new FrmPhotoMove();
                fpm.UserId = userId;
                fpm.Manage = this;
                fpm.StartPosition = FormStartPosition.CenterScreen;
                fpm.WindowState = FormWindowState.Minimized;
                fpm.Show();
            }
        }
        //关闭照片移动页面
        public void CloseMovePhoto()
        {
            fpm.notifyIcon1.Visible = false;
            fpm.RecoverBingFa();
            fpm.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //OpenMovePhoto();
            RushPanlOrderInfoStatus();
        }

        private void RushPanlOrderInfoStatus()
        {
            this.palOrderInfoStatus.Controls.Clear();

            //从数据库中获取目前的大板状态的数量
            int lblIndex = 0, lblWidth = 0;
            Point lblLocation = new Point(5, 14);

            var resultList = BoardStatsMonitorBLL.GetALLOrderInfoStatusQutiy();
            foreach (var msg in resultList)
            {
                Label lbl = new Label();
                lbl.Name = "lbl" + lblIndex;
                lbl.Text = msg;
                if (lblIndex != 0)
                {
                    lblLocation = new Point(lblLocation.X + lblWidth + 5, 14);
                }
                lblIndex++;
                lbl.Location = lblLocation;
                lblWidth = lbl.Size.Width;
                if (msg.Contains("错误"))
                {
                    lbl.ForeColor = Color.Red;
                }
                palOrderInfoStatus.Controls.Add(lbl);
            }
        }

        #region 快速筛选清除按钮
        private void btnClearFastFind_Click(object sender, EventArgs e)
        {
            try
            {
                ClearFastFind();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion
        #region 清除快速筛选条件
        /// <summary>
        /// 清除快速筛选条件
        /// </summary>
        public void ClearFastFind()
        {
            try
            {
                cmbOrderName.Text = "";
                cmbOrderCode.Text = "";
                cmbPriority1.Text = "";
                dtOrderStart.Text = "";
                dtFetchStart.Text = "";
                //cmbFlowList.Text = "";
                cmbFlowList.EditValue = -1;
                cmbOperator.Text = "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //产品与其照片是否匹配
        private void gridViewPhotoInfo_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                if (currentStyleProduct == null)
                    return;
                PhotoInfoEntity photo = gridViewPhotoInfo.GetRow(e.RowHandle) as PhotoInfoEntity;
                if (currentStyleProduct.ProductTypeCode == (int)OrderInfoProductType.NoNeedDesignProduct && photo != null)
                {
                    if ((photo.Height <= currentStyleProduct.MaxHeight && photo.Height >= currentStyleProduct.MinHeight) || (photo.Width <= currentStyleProduct.MaxWidth && photo.Width >= currentStyleProduct.MinWidth))
                    {

                    }
                    else
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //删除订单，这里是标记删除
        private void tsDelOrder_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.gridViewOrder.SelectedRowsCount > 0)
                {
                    OrderBagEntity item = (OrderBagEntity)this.gridViewOrder.GetFocusedRow();
                    if (item.StatusValue == (int)COM.OrderBagStatus.Completed)
                    {
                        MessageBox.Show("订单已完成，不能删除！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (_focusOrderInfo != null)
                    {
                        if (DialogResult.Yes == MessageBox.Show("确定要删除产品号为：" + _focusOrderInfo.OrderProductId + "的产品吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            int rtnVla = _controller.DeleteOrderBag(item.OrderBagID, _focusOrderInfo.OrderProductId, userId);
                            if (rtnVla == 1)
                            {
                                MessageBox.Show("删除成功！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }

                        }

                    }
                    else
                    {
                        if (DialogResult.Yes == MessageBox.Show("此定单下的所有产品都将被删除，确定要删除该订单：" + item.BagCode + "吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            int rtnVla = _controller.DeleteOrderBag(item.OrderBagID, userId);
                            if (rtnVla == 1)
                            {
                                MessageBox.Show("删除成功！", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            barButtonItem1_ItemClick(sender, e);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //产品列表
        private void tsOrderInfo_Click(object sender, EventArgs e)
        {
            OrderInfo.FrmOrderInfo info = OrderInfo.FrmOrderInfo.GetInstance;
            info.Manage = this;
            info.Show();
        }

        //质检(暂时删除)
        private void tsCheckOrderInfo_Click(object sender, EventArgs e)
        {
            OrderInfo.FrmCheckOrderInfo check = OrderInfo.FrmCheckOrderInfo.GetInstance;
            check.Show();
        }

        //审核自动开单
        private void tsCheckAutoStartOrder_Click(object sender, EventArgs e)
        {
            FtpUpload.FrmCheckAutoOrder frm = FtpUpload.FrmCheckAutoOrder.GetInstance;
            frm.Show();
        }

        //产品的照片数量
        private void gridPhotoInfo_DataSourceChanged(object sender, EventArgs e)
        {
            try
            {
                if (gridPhotoInfo.DataSource != null)
                    lblPhotoCount.Text = gridViewPhotoInfo.RowCount.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //显示订单内缩略图
        private void btnShowOrderImg_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                _controller.GetDefaultBagImage();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        // 通信
        private void tsCommunicate_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ComControls.frmMain frm = ComControls.frmMain.GetInstance(userId);
                frm.Show();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //单击产品路径
        private void gridViewProduct_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (e.RowHandle >= 0 && e.Column.FieldName == "OrderPath")
                {
                    GridView view = sender as GridView;
                    OrderInfoEntity p = view.GetRow(e.RowHandle) as OrderInfoEntity;
                    string infoPath = p.OrderPath;
                    ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                             new StringBuilder(infoPath), new StringBuilder(string.Empty), 1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //理件界面
        private void tsDispose_Click(object sender, EventArgs e)
        {
            try
            {
                DisposePhoto.FrmDisposeMain frm = DisposePhoto.FrmDisposeMain.GetInstance;
                frm.UserId = userId;
                frm.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //财务强制审核通过那些等待付款的产品
            if (this._focusOrderInfo != null)
            {
                if (_focusOrderInfo.StatusValue == (int)OrderInfoStatus.WaitPay || _focusOrderInfo.StatusValue == (int)OrderInfoStatus.WaitCheck || _focusOrderInfo.StatusValue == (int)OrderInfoStatus.WaitPayAndWaitMovePhoto)
                {
                    if (MessageBox.Show("确定要使欠款的产品恢复生产？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        if (DialogResult.Yes == MessageBox.Show("确定要强制进行行产", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                        {
                            _controller.SetOrderToProduct(_focusOrderInfo, _focusOrderBag);
                        }
                    }
                }
            }
        }

        private void gridView2_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.Name == "gridColumn10")
            {
                try
                {
                    Process.Start(e.CellValue.ToString());
                }
                catch
                {
                    MessageBox.Show("找不到图片：\r\n" + e.CellValue.ToString());
                }

            }
        }

        private void gridControlOrders_Click(object sender, EventArgs e)
        {

        }

        private void gridViewPhotoInfo_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (e.RowHandle >= 0 && e.Column.FieldName == "picPath")
                {
                    GridView view = sender as GridView;
                    PhotoInfoEntity p = view.GetRow(e.RowHandle) as PhotoInfoEntity;
                    string infoPath = p.picPath;
                    ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("explorer.exe"),
                                             new StringBuilder(infoPath), new StringBuilder(string.Empty), 1);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void toolStripButtonOutReturn_Click(object sender, EventArgs e)
        {
            FrmShortOutReturn frm = new FrmShortOutReturn(userId);
            frm.Show();

        }

        private void tsbtnPrintTickt_Click(object sender, EventArgs e)
        {
            OrderBagEntity orderBag = (OrderBagEntity)gridViewOrder.GetFocusedRow();
            if (orderBag != null)
            {
                if (orderBag.StatusValue == (int)OrderBagStatus.Doing)
                {
                    _controller.PrintTicket(orderBag.OrderBagID, userName, orderBag.ShopName);
                }
                else
                {
                    MessageBox.Show("只能打印正在生产中的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("请选择要打单的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void palOrderInfoStatus_Paint(object sender, PaintEventArgs e)
        {

        }

        private void backgroundWorkerFindDely_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 6; i++)
            {
                //switch (i)
                //{
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyOne:
                //        break;
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyTwo:
                //        break;
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyMore:
                //        break;
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.Stop:
                //        break;
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.ShenHe:
                //        break;
                //    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.JiaJi:
                //        break;
                //}
                // GetProductNum
                int val = _controller.GetProductNum(i);
                backgroundWorkerFindDely.ReportProgress(i, val);

            }
        }

        private void timerDelyFinder_Tick(object sender, EventArgs e)
        {
            backgroundWorkerFindDely.RunWorkerAsync();
        }

        private void backgroundWorkerFindDely_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                int style = e.ProgressPercentage;
                int Num = (int)e.UserState;
                switch (style)
                {
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyOne:
                        linkLabelDely1.Text += " " + Num;
                        break;
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyTwo:
                        linkLabelDely2.Text += " " + Num;
                        break;
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.DelyMore:
                        linkLabelDelyMore.Text += " " + Num;
                        break;
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.Stop:
                        linkLabelStop.Text += " " + Num;
                        break;
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.ShenHe:
                        linkLabelShenhe.Text += " " + Num;
                        break;
                    case (int)MINERP.BLL.CustomerManage.OrderInfoBLL.OrderQueryStyle.JiaJi:
                        linkLabel1.Text += " " + Num;
                        break;
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void linkLabelDely1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //MessageBox.Show("不要着急马上更新哦");
        }

        private string[] GetFilesPath(string dirPath)
        {
            string[] file1 = Directory.GetFiles(dirPath, "*.jpg");
            string[] file2 = Directory.GetFiles(dirPath, "*.tif");
            string[] file3 = Directory.GetFiles(dirPath, "*.jpeg");
            string[] file4 = Directory.GetFiles(dirPath, "*.tiff");
            string[] files = file1.Concat(file2).Concat(file3).Concat(file4).ToArray();
            return files;
        }

        private FileInfo[] GetFileInfo(string dirPath)
        {
            DirectoryInfo ssubInfo = new DirectoryInfo(dirPath);
            FileInfo[] sssfile1 = ssubInfo.GetFiles("*.jpg");
            FileInfo[] sssfile2 = ssubInfo.GetFiles("*.tif");
            FileInfo[] sssfile3 = ssubInfo.GetFiles("*.jpeg");
            FileInfo[] sssfile4 = ssubInfo.GetFiles("*.tiff");
            FileInfo[] sssfile = sssfile1.Concat(sssfile2).Concat(sssfile3).Concat(sssfile4).ToArray();
            return sssfile;
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            //OrderBagEntity orderBag = (OrderBagEntity)gridViewOrder.GetFocusedRow();
            //if (orderBag != null)
            //{
            //    if (orderBag.StatusValue == (int)OrderBagStatus.Doing)
            //    {
            //        _controller.PrePrintBill(orderBag.OrderBagID);
            //    }
            //    else
            //    {
            //        MessageBox.Show("只能打印正在生产中的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
            //else
            //{
            //    MessageBox.Show("请选择要打单的订单!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            FrmPrePrintBill frmpb = new FrmPrePrintBill();
            frmpb.ShowDialog();

        }
    }
}
